﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace CZ.PAEZ.SaleManager.ListPlugIns
{
    [Description("提货联列表获取发票号")]
    [HotUpdate]
    public class PickGoodsList : AbstractListPlugIn
    {
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            switch (e.BarItemKey.ToUpperInvariant())
            {
                case "PAEZ_TBGETINVOICE": // PAEZ_tbGetInvoice 获取发票号
                    Act_ABIC_GetInvoices(e);
                    break;
            }
        }

        private void Act_ABIC_GetInvoices(AfterBarItemClickEventArgs e)
        {
            var rows = this.ListView.SelectedRowsInfo.DistinctBy(i => i.PrimaryKeyValue).ToList();
            if (rows.Count <= 0)
            {
                this.View.ShowErrMessage("请选中要生成发票的行！");
                return;
            }
            // 获取金税盘号
            GetGoldTaxDiskNo((taxDiskNo) =>
            {
                string msg = "";
                foreach (var row in rows)
                {
                    if (!row.DataRow["FInvoice"].IsNullOrEmptyOrWhiteSpace())
                    {
                        msg += $"编号为：{row.BillNo}的提货联，已经存在发票号，跳过获取！\n";
                        continue;
                    }
                    string sql = string.Format(@"/*dialect*/
select top 1 ip.FID, ip.FNumber, ip.FInvoiceLot from (select * from PAEZ_t_Lading where FID={0}) l
inner join T_BD_CUSTOMER c on c.FCUSTID=l.FCustomerID
inner join PAEZ_BD_InvoicePool ip on ip.FInvoiceType=c.FInvoiceType
where ip.FIsUsed=0 and ip.FTaxDiskNo1={1}
order by Convert(bigint, ip.FNumber) asc
", row.PrimaryKeyValue, taxDiskNo);
                    var info = DBUtils.ExecuteDynamicObject(Context, sql);
                    if (info.Count <= 0)
                    {
                        msg += $"编号为：{row.BillNo}的提货联，发票号获取失败，请检查发票池是否存有未使用的发票号！\n";
                        continue;
                    }
                    sql = string.Format(@"/*dialect*/
update l set FInvoice='{2}',FInvoiceLot='{3}',FTaxDiskNo='{4}' from PAEZ_t_Lading l where FID={0};
update ip set FIsUsed=1 from PAEZ_BD_InvoicePool ip where FID={1};",
    row.PrimaryKeyValue, info[0]["FID"], info[0]["FNumber"], info[0]["FInvoiceLot"], taxDiskNo);
                    DBUtils.Execute(Context, sql);
                }

                if (msg.Equals(""))
                {
                    this.View.ShowMessage("发票号获取成功！");
                }
                else
                {
                    this.View.ShowWarnningMessage(msg, "执行完毕，但存在部分单据的发票号获取失败或无需获取！");
                }
                this.View.Refresh();
            });
        }


        /// <summary>
        /// 获取金税盘号
        /// </summary>
        /// <param name="callback"></param>
        private void GetGoldTaxDiskNo(Action<string> callback)
        {
            var param = new DynamicFormShowParameter();
            param.FormId = "PAEZ_GoldTaxChoice";
            param.ParentPageId = this.View.PageId;
            param.OpenStyle.ShowType = ShowType.Modal;

            this.View.ShowForm(param, result =>
            {
                if(result.ReturnData.IsNullOrEmptyOrWhiteSpace())
                {
                    this.View.ShowWarnningMessage("未选择有效的金税盘号！");
                    return;
                }
                callback(result.ReturnData.ToString());

            });
        }
    }
}
